var express = require("express");
var router = express.Router();
var axios = require("axios");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

//向小程序发送订阅消息
router.get("/sendmsg", async function (req, res, next) {
  console.log(req);
  let token = await axios({
    url: "https://api.weixin.qq.com/cgi-bin/token",
    method: "GET",
    data: {
      grant_type: "client_credential",
      appid: "wx759ba279af47d3bb",
      secret: "3edbda305a2572dc3e57ed16fef69c04",
    },
  });
  let { access_token } = token.data; //得到后端下发的access_token
  let send = await axios({
    url: `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`,
    method: "POST",
    data: {
      template_id: "pB2U2xhgsNuE70yMFGWbeB7XbJLpS6Uln4tleBJDu8g", //消息模板id
      touser: req.query.openid, //目标用户openid
      page: "/pages/explore/index",
      miniprogram_state: "trail", //开发版
      lang: "zh_CN",
      data: {
        thing5: {
          value: "您还有500万大奖待领取",
        },
        date3: {
          value: "2023年8月30",
        },
      },
    },
  });
  console.log(send);
  res.send({
    msg: "发送成功",
    openid: req.query.openid,
  });
});

module.exports = router;
